import config from '@/utils/config.js'
import { notice } from '@/utils/common.js'

//配置
const rqConfig = {
	baseUrl: config.baseUrl,
	timeout: 60000,
}

//响应拦截
const responseIntercept = function(response) {		
	const data = response.data
	return data
}

//请求拦截
const requestIntercept = function() {
	let authToken = uni.getStorageSync("_app_token")
	return {
		header: {
			'X-Authorization-access_token' : authToken
		}
	}
}

//请求
const service = {
	_basis(opt, success, fail) {
		const defaultOption = {
			loading : true,
			showFailMsg : true
		}
		
		const nOption = opt ? Object.assign(defaultOption , opt) : defaultOption;
		
		let {
			url,
			params,
			method,
			pager,
			type
		} = nOption
		
		let data = {}
		
		if (params) {
			let parameter = ''
			for (const name in params) {
				if(params[name] !== undefined && params[name] !== null)				
					parameter += `&${name}=${encodeURIComponent(params[name])}`;
			}
			if (parameter !== '') {
				parameter = parameter.substr(1);
				url += url.includes('?') ? '' : '?' + parameter;
			}
			
			if(type){
				data.parameters = params
			}else{
				data = params
			}
		}
		
		if(pager) {
			data.requestPage = {
				limit: pager.limit,
				pageNo: pager.start
			}
		}
		
		const enableLoading = getApp() && !getApp().globalData.disableLoading;
		
		if (enableLoading && nOption.loading) {	
			notice.showLoading();
		}
		
		const requestOpt = {
			url: `${url}`,
			data,
			method,
			success: (res) => {
				if (enableLoading && nOption.loading) {
					notice.hideLoading();
				}
				
				const resData = responseIntercept(res);
				
				//DBUGE调试
				console.log('%c 请求api: ' + url,'color:red');
				console.log('%c 返回值: ' ,'color:red' , resData);
				
				if(!resData) return;
				if(resData.code === 200 || resData.state === 200) {
					success && success(resData);
				} else {					
					if(nOption.showFailMsg) {
						notice.toast(resData.message || '服务器异常,请稍后再试');
					}
					fail && fail(resData ? resData.message : '')
				}
			},
			fail: (res) => {
				if (enableLoading && nOption.loading) {
					notice.hideLoading();
				}
				notice.toast(JSON.stringify(res));	
			}
		}
		return uni.request(Object.assign(requestOpt, requestIntercept()));
	},
	post(opt) {
		opt.method = 'POST'
		return new Promise((resolve, reject) => {			
			this._basis(opt, resolve, reject)
		})
	},
	get(opt) {
		opt.method = 'GET'
		return new Promise((resolve, reject) => {
			this._basis(opt, resolve, reject)
		})
	}
}

export default service